<template>
  <a-modal
    title="品检部审核"
    :width="1500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    :okButtonProps="{ props: { disabled: disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
    style="top: 20px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="5" :sm="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="请选择">
              <j-dict-select-tag
                v-decorator="['channelFlag', validatorRules.status]"
                @change="handleWarehouseFlag"
                :type="'radioButton'"
                :triggerChange="true"
                dictCode="OmsReturnInspectionApprove_status"
              />
            </a-form-item>
          </a-col>
          <a-col :md="10" :sm="12">
            <a-form-item
              :hidden="model.channelFlag == '111'"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="审核意见">
              <a-textarea v-if="model.channelFlag != '111'" :rows="1" placeholder="请输入审核意见"
                          v-decorator="['note', validatorRules.note]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-descriptions title="" bordered style="margin-bottom: 24px" :column="{md: 2,sm: 2}" >
        <a-descriptions-item label="检测报告" >
          <a-row :gutter="30">
            <a-col :md="2" :sm="12">
              <a-upload
                :showUploadList="false"
                :action="uploadAction"
                :data="{'isup':1,'dir':'returnOrder/file'}"
                :headers="headers"
                :beforeUpload="beforeUpload"
                @change="handleChange"
              >
                <a-button type="primary">上传</a-button>
              </a-upload>
            </a-col>
            <a-col :md="10" :sm="12">
              <div :key="index" v-for="(file, index) in inspectionReportList">
                <a :href="file.url" target="_blank">{{ file.name }}</a> <a style="padding-left: 10px" href="#"
                                                                           @click="deleteFile(index)">删除</a>
              </div>
            </a-col>
          </a-row>
        </a-descriptions-item>
      </a-descriptions>

      <div class="title">退货申请信息</div>
      <a-table
        style="margin-bottom: 24px"
        rowKey="id"
        bordered
        :scroll="{ x: 800 }"
        :columns="returnGoodsColumns"
        :pagination="false"
        :dataSource="returnOrderEditColumns2">
        <div slot="returnFileList" slot-scope="returnFileList, row">
          <div :key="index" v-for="(file, index) in returnFileList">
            <a :href="file.url" target="_blank">{{ file.name }}</a>
          </div>
        </div>
      </a-table>

      <div class="title">审核信息</div>
      <a-table
        size="middle"
        bordered
        :columns="goodsColumns"
        :dataSource="returnOrderEditColumns"
        :scroll="{ y: 440 }"
        :pagination="false"
        :loading="loading"
      >
        <div slot="uselessSkuUnitQuantity" slot-scope="uselessSkuUnitQuantity, row">
          <a-input-number
            id="inputNumber1"
            :value="uselessSkuUnitQuantity"
            :min="0"
            @change="onChangeUselessSkuUnitQuantity($event, row)"
            :precision="0"
          />
        </div>
        <div slot="uselessUnitQuantity" slot-scope="uselessUnitQuantity, row">
          <a-input-number
            id="inputNumber2"
            :precision="0"
            :value="uselessUnitQuantity"
            :min="0"
            @change="onChangeUselessUnitQuantity($event, row)"
          />
        </div>
        <div slot="reuseSkuUnitQuantity" slot-scope="reuseSkuUnitQuantity, row">
          <a-input-number
            id="inputNumber3"
            :precision="0"
            :value="reuseSkuUnitQuantity"
            :min="0"
            @change="onChangeReuseSkuUnitQuantity($event, row)"
          />
        </div>
        <div slot="reuseUnitQuantity" slot-scope="reuseUnitQuantity, row">
          <a-input-number
            id="inputNumber4"
            :precision="0"
            :value="reuseUnitQuantity"
            :min="0"
            @change="onChangeReuseUnitQuantity($event, row)"
          />
        </div>
        <div slot="refuseSkuUnitQuantity" slot-scope="refuseSkuUnitQuantity, row">
          <a-input-number
            id="inputNumber5"
            :precision="0"
            :value="refuseSkuUnitQuantity"
            :min="0"
            @change="onChangeRefuseSkuUnitQuantity($event, row)"
          />
        </div>
        <div slot="refuseUnitQuantity" slot-scope="refuseUnitQuantity, row">
          <a-input-number
            id="inputNumber6"
            :precision="0"
            :value="refuseUnitQuantity"
            :min="0"
            @change="onChangeRefuseUnitQuantity($event, row)"
          />
        </div>
      </a-table>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from "lodash.pick";
import {httpAction, postAction} from "@/api/manage";
import {getAction} from "@/api/manage";
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {mergeSameProducts} from '@/utils/util'

export default {
  name: "OrderReturnApplyInspectionApprove",

  data() {
    return {
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      approveStatus: 5,
      applyId: 0,
      instructionList: [],
      inspectionReportList: [],
      returnOrderEditColumns2:[],
      form: this.$form.createForm(this),
      validatorRules: {
        status: {rules: [{required: true, message: "请选择状态!"}]},
        note: {rules: [{required: true, message: '请输入审核意见!'}]},
      },
      labelCol: {
        xs: {span: 24},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 13},
      },
      type: 1,
      returnOrderEditColumns: [],
      goodsColumns: [
        {
          title: "商品名称",
          key: "productName",
          dataIndex: "productName",
          customRender: (value, row, index) => {
            const obj = {
              children: value,
              attrs: {},
            };
            if (row.showName) {
              obj.attrs.rowSpan = row.rowSpan;
            } else if(row.hideName){
              obj.attrs.rowSpan = 0;
            } 
           
            return obj;
          },
        },
        {
          title: "批次号",
          key: "batchNo",
          dataIndex: "batchNo",
        },
        {
          title: "物流实收（整箱）",
          key: "realReturnSkuUnitCount",
          dataIndex: "realReturnSkuUnitCount",
        },
        {
          title: "物流实收（零散）",
          key: "realReturnUnitCount",
          dataIndex: "realReturnUnitCount",
        },
        {
          title: "品检报废(整箱)",
          key: "uselessSkuUnitQuantity",
          dataIndex: "uselessSkuUnitQuantity",
          scopedSlots: {customRender: "uselessSkuUnitQuantity"},
        },
        {
          title: "品检报废(零散)",
          key: "uselessUnitQuantity",
          dataIndex: "uselessUnitQuantity",
          scopedSlots: {customRender: "uselessUnitQuantity"},
        },
        {
          title: "品检返仓(整箱)",
          key: "reuseSkuUnitQuantity",
          dataIndex: "reuseSkuUnitQuantity",
          scopedSlots: {customRender: "reuseSkuUnitQuantity"},
        },
        {
          title: "品检返仓(零散)",
          key: "reuseUnitQuantity",
          dataIndex: "reuseUnitQuantity",
          scopedSlots: {customRender: "reuseUnitQuantity"},
        },
        {
          title: "品检不予退货(整箱)",
          key: "refuseSkuUnitQuantity",
          dataIndex: "refuseSkuUnitQuantity",
          scopedSlots: {customRender: "refuseSkuUnitQuantity"},
        },
        {
          title: "品检不予退货(零散)",
          key: "refuseUnitQuantity",
          dataIndex: "refuseUnitQuantity",
          scopedSlots: {customRender: "refuseUnitQuantity"},
        },

      ],
      returnGoodsColumns: [
        {
          title: '商品名称',
          key: 'productName',
          width: 150,
          dataIndex: 'productName'
        },
        {
          title: '物料编码',
          key: 'productSkuCode',
          width: 140,
          dataIndex: 'productSkuCode'
        },
        {
          title: '箱规',
          key: 'productSpecUnit',
          width: 100,
          dataIndex: 'productSpecUnit'
        },
        {
          title: '单价',
          key: 'unitPrice',
          width: 80,
          dataIndex: 'unitPrice'
        },
        {
          title: '箱装价',
          key: 'skuUnitPrice',
          width: 100,
          dataIndex: 'skuUnitPrice'
        },
        {
          title: '申请数量(整箱)',
          key: 'returnSkuUnitCount',
          width: 130,
          dataIndex: 'returnSkuUnitCount'
        },
        {
          title: '申请数量(零散)',
          key: 'returnUnitCount',
          width: 130,
          dataIndex: 'returnUnitCount'
        },
        {
          title: '数量小计',
          key: 'minUnitQuantityCount',
          width: 90,
          dataIndex: 'minUnitQuantityCount'
        },
        {
          title: '小计金额',
          key: 'totalAmount',
          width: 100,
          dataIndex: 'totalAmount'
        },
        {
          title: '申请原因',
          key: 'reason',
          width: 140,
          dataIndex: 'reason'
        },
        {
          title: '申请凭证',
          key: 'returnFileList',
          width: 140,
          dataIndex: 'returnFileList',
          scopedSlots: {customRender: "returnFileList"},
        },
      ],
      url: {
        approve: "/returns/omsOrderReturnApply/inspectionApprove",
        returnOrderItem: "/returns/omsOrderReturnItem/returnOrderItem",
        fileUpload: window._CONFIG['domianURL'] + "/sys/common/ossUpload",
        returnBatchOrderItem: "/returns/omsOrderReturnItemBatch/returnBatchOrderItem",
      },
      loading: false,
    };
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token": token};
  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    }
  },
  methods: {
    show(record) {
      this.instructionList = [];
      this.inspectionReportList = [];
      this.visible = true;
      this.model = Object.assign({}, record);
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, "channelFlag", 'note', "reason"));
      });
      if (record != {} && record.returnCertificate != null && record.returnCertificate.length > 0) {
        this.instructionList = eval(record.returnCertificate);
      }
      this.model.channelFlag = 7;
      this.applyId = record.id;
      if (this.applyId) {
        this.loadGoodsData();
        this.loadReturnBatchData();
      }
    },
    loadGoodsData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnOrderItem, params).then((res) => {
        if (res.success) {
          this.returnOrderEditColumns2 = res.result;
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    loadReturnBatchData() {
      var params = {applyId: this.applyId};
      this.loading = true;
      getAction(this.url.returnBatchOrderItem, params).then((res) => {
        if (res.success) {
          this.returnOrderEditColumns = mergeSameProducts(res.result);
        }
        if (res.code === 510) {
          this.$message.warning(res.message);
        }
        this.loading = false;
      });
    },
    close() {
      this.form.resetFields();
      this.$emit("close");
      this.visible = false;
    },
    handleSubmit() {
      this.confirmLoading = true;
      this.approveStatus = this.model.channelFlag;
      let itemList = [];
      this.returnOrderEditColumns.forEach((row) => {
        const {
          uselessSkuUnitQuantity,
          uselessUnitQuantity,
          reuseSkuUnitQuantity,
          reuseUnitQuantity,
          refuseSkuUnitQuantity,
          refuseUnitQuantity,
          id,
          productId
        } = row;
        itemList.push({
          uselessSkuUnitQuantity,
          uselessUnitQuantity,
          reuseSkuUnitQuantity,
          reuseUnitQuantity,
          refuseSkuUnitQuantity,
          refuseUnitQuantity,
          id,
          productId
        });

      });

      // if (this.inspectionReportList.length == 0) {
      //   this.$message.warning("请上传检测报告");
      //   this.confirmLoading = false;
      //   return;
      // }

      let formData = {
        status: this.approveStatus,
        id: this.applyId,
        approveComments: this.form.getFieldValue("note"),
        inspectionReport: JSON.stringify(this.inspectionReportList),
        itemList,
      };
      this.form.validateFields((err, values) => {
        if (!err) {
          postAction(this.url.approve, formData)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.$emit("ok");
                this.close();
              } else {
                this.$message.warning(res.message);
              }
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        }
      });
      this.confirmLoading = false;
    },
    handleCancel() {
      this.close();
    },
    handleWarehouseFlag(e) {
      this.model.channelFlag = e;
    },
    onChangeUselessSkuUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      console.log(4444444)
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < event) {
        return;
      }
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < row.reuseSkuUnitQuantity + row.refuseSkuUnitQuantity + event) {
        return;
      }
      row.uselessSkuUnitQuantity = event;
    },
    onChangeUselessUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      console.log(777777777)
      let totalSkuUnitCount = row.reuseSkuUnitQuantity + row.refuseSkuUnitQuantity + row.uselessSkuUnitQuantity;
      let totalUnitCount = event + row.reuseUnitQuantity + row.refuseUnitQuantity;

      if (parseInt(row.realUnitQuantity / row.productSkuSpec) == totalSkuUnitCount && totalUnitCount > row.realUnitQuantity % row.productSkuSpec) {
        return;
      }
      row.uselessUnitQuantity = event;
    },
    onChangeReuseSkuUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      console.log(66666)
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < event) {
        return;
      }
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < row.uselessSkuUnitQuantity + row.refuseSkuUnitQuantity + event) {
        return;
      }
      row.reuseSkuUnitQuantity = event;
    },
    onChangeReuseUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      let totalSkuUnitCount = row.reuseSkuUnitQuantity + row.refuseSkuUnitQuantity + row.uselessSkuUnitQuantity;
      let totalUnitCount = event + row.uselessUnitQuantity + row.refuseUnitQuantity;
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) == totalSkuUnitCount && totalUnitCount > row.realUnitQuantity % row.productSkuSpec) {
        return;
      }
      row.reuseUnitQuantity = event;
    },
    onChangeRefuseSkuUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      console.log(444444444)
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < event) {
        return;
      }
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) < row.reuseSkuUnitQuantity + row.uselessSkuUnitQuantity + event) {
        return;
      }
      row.refuseSkuUnitQuantity = event;
    },
    onChangeRefuseUnitQuantity(event, row) {
      if (event === "" || event == null) {
        return;
      }
      let totalSkuUnitCount = row.reuseSkuUnitQuantity + row.refuseSkuUnitQuantity + row.uselessSkuUnitQuantity;
      let totalUnitCount = event + row.uselessUnitQuantity + row.reuseUnitQuantity;
      if (parseInt(row.realUnitQuantity / row.productSkuSpec) == totalSkuUnitCount && totalUnitCount > row.realUnitQuantity % row.productSkuSpec) {
        return;
      }
      row.refuseUnitQuantity = event;
    },
    beforeUpload: function (file) {
      var fileType = file.type;
      //TODO 验证文件大小
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true;
        return
      }
      if (info.file.status === 'done') {
        var response = info.file.response;
        this.uploadLoading = false;
        console.log(response);
        if (response.success) {
          this.inspectionReportList.push({name: response.result.fileName, url: response.result.url});
        } else {
          this.$message.warning(response.message);
        }
      }
    },
    deleteFile(index) {
      this.inspectionReportList.splice(index, 1);
    },
  },
};
</script>
<style>
.ant-descriptions-item-label {

  width: 180px;
}
.title {
  margin-bottom: 10px;
  font-weight: bold;
  line-height: 1.5;
}
</style>